<template>
  <el-dialog
    ref="table"
    :title="title"
    :visible.sync="visible"
    :before-close="closeDlg"
    :close-on-click-modal="false"
    destroy-on-close="true"
    style="margin-top: -60px"
    :width="width"
  >
    <el-table
      ref="dragTable"
      v-loading="listLoading"
      :data="list"
      row-key="ID"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="610"
      @current-change="handleCurrentChange"
      :row-style="rowClass"
      :row-class-name="tableClass"
    >
<!--      <el-table-column label="名称" width="" align="" show-overflow-tooltip>-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{ row.name }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="简称" width="100" align="" show-overflow-tooltip>-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{ row.shortName }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="序号" width="60" align="">
        <template slot-scope="{row}">
          <span>{{ row.orderSeq}}</span>
        </template>
      </el-table-column>
      <el-table-column label="中心频率(Hz)" width="260" align="">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input-freq
              v-model="row.centerFrequency"
              style="width: 235px"
              :isPositive="true"
            />
          </template>
          <span v-else>{{ row.centerFrequency != null ? controlAmount(row.centerFrequency) : ''}}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="频率带宽(Hz)" width="" align="">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{ controlAmount(row.bandWidth)}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="耦合度" width="" align="">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.coupling" class="edit-input" style="width: 135px" />
          </template>
          <span v-else>{{ row.coupling}}</span>
        </template>
      </el-table-column>
      <el-table-column label="损耗" width="" align="">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.loss" class="edit-input" style="width: 135px" />
          </template>
          <span v-else>{{ row.loss}}</span>
        </template>
      </el-table-column>
      <el-table-column label="增益" width="" align="">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.gain" class="edit-input" style="width: 135px" />
          </template>
          <span v-else>{{ row.gain}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="" :width="90 / 2 + 5" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <!--                <el-button type="primary" size="mini" @click="handleUpdate(row)">-->
          <!--                  {{ $t('table.edit') }}-->
          <!--                </el-button>-->
          <!--              <el-button size="mini" type="danger" @click="handleDelete(row)">-->
          <!--                {{ $t('table.delete') }}-->
          <!--              </el-button>-->
<!--          <img-->
<!--            v-if="!row.edit"-->
<!--            class="listIcon"-->
<!--            title="编辑"-->
<!--            :src="listIcon.update"-->
<!--            alt=""-->
<!--            @click="row.edit=!row.edit"-->
<!--          />-->
<!--          <img-->
<!--            v-if="row.edit"-->
<!--            class="listIcon"-->
<!--            title="取消"-->
<!--            :src="listIcon.cancelPaper"-->
<!--            alt=""-->
<!--            @click="cancelEdit(row)"-->
<!--          />-->
<!--          <img-->
<!--            v-if="row.edit"-->
<!--            class="listIcon"-->
<!--            title="确认"-->
<!--            :src="listIcon.qianzi"-->
<!--            alt=""-->
<!--            @click="confirmEdit(row)"-->
<!--          />-->
          <img
            class="listIcon"
            title="删除"
            :src="listIcon.delete"
            alt=""
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--    对话框下方按钮-->
    <div slot="footer" class="dialog-footer">
      <!--    取消按钮-->
      <!--      <el-button @click="closeDlg">-->
      <!--        {{ $t('table.cancel') }}-->
      <!--      </el-button>-->

      <el-button
        type="primary"
        icon="el-icon-document"
        :loading="downloadLoading"
        @click="handleDownload"
      >
        {{ $t('excel.export') }} Excel
      </el-button>
      <el-button
        type="success"
        @click="save"
        :loading="loadingBtn"
      >
        保存
      </el-button>
      <el-button
        type="success"
        @click="createData"
        :loading="loadingBtn"
      >
        添加
      </el-button>
      <el-button type="warning" @click="closeDlg">
        关闭
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getChainFrequencyDataList } from '@/api/weixing/base'
import global from '@/common'
import { controlAmount, isNotEmpty, zEnBase64 } from '@/utils'
import { fetchList } from '@/api/system/article'
import { getToken } from '@/utils/auth'
import {
  createChainFrequencyData, deleteChainFrequencyData,
  updateChainFrequencyData,
  UploadChainFrequencyData
} from '@/api/weixing/chainFrequencyData'
import moment from 'moment'
import ElInputFreq from '@/common/weixing/components/ElInputFreq/index'
import { fetchChainOne } from '@/api/weixing/chain'

export default {
  name: 'ChainFreqData',
  components: { ElInputFreq },
  props: {
    width: {
      type: String,
      default: '900px'
    },
    height: {
      type: String,
      default: '600px'
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '链路频率校准数据'
    },
    row: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      list: null, // 列表数据
      listLoading: true, // 列表状态为加载中
      loadingBtn: false, // 防止表单重复提交
      downloadLoading: false,
      loadingBtnTitle: '确定', // 提交按钮标题
      dialogStatus: 'create',
      currentRow: {},
      selectedIndex: 0,
      listIcon: global.listIcon, // 列表按钮图标
      excel: {
        filename: '链路频率校准数据【' + this.row.name + '】' + moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        autoWidth: true,
        bookType: 'xls'
      }
    }
  },
  created() {
    console.log(this.row)
    this.title = '链路频率校准数据【' + this.row.name + '】'
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const { body, header } = await getChainFrequencyDataList(
        'applicationID=' + this.row.applicationID +
        ',organizationID=' + this.row.organizationID +
        ',chainFrequencyDefineID=' + this.row.ID,
        'orderSeq,' +
        'name,shortName,centerFrequency,bandWidth,coupling,loss,gain',
        'centerFrequency=1'
      )
      console.log(header)
      console.log(body)
      if (header.code === 0) {
        const items = body.data.rows
        this.list = items.map(v => {
          this.$set(v, 'edit', true) // https://vuejs.org/v2/guide/reactivity.
          this.$set(v, 'centerFrequency', v.centerFrequency != null ? controlAmount(v.centerFrequency) : '')
          // v.originalTitle = v.title //  will be used when user click the cancel botton
          return v
        })
        this.listLoading = false
      }
    },
    cancelEdit(row) {
      // row.title = row.originalTitle
      row.edit = false
      this.getList()
      // this.$message({
      //   message: 'The title has been restored to the original value',
      //   type: 'warning'
      // })
    },
    async createData() {
      // await this.getList()
      this.loadingBtn = true
      let params = ''
      params += 'chainFrequencyDefineID=' + zEnBase64(this.row.ID)
      if (isNotEmpty(this.row.applicationID)) { params += ',applicationID=' + zEnBase64(this.row.applicationID) }
      if (isNotEmpty(this.row.organizationID)) { params += ',organizationID=' + zEnBase64(this.row.organizationID) }
      if (isNotEmpty(this.row.stationID)) { params += ',stationID=' + zEnBase64(this.row.stationID) }
      if (isNotEmpty(this.row.chainID)) {
        params += ',chainID=' + zEnBase64(this.row.chainID)
        const { body } = await fetchChainOne({ token: getToken(), ID: this.row.chainID })
        params += ',shortName=' + zEnBase64(body.data.name)
      }
      params += ',name=' + zEnBase64(this.row.name)
      if (this.list.length > 0) {
        params += ',orderSeq=' + zEnBase64(this.list[this.list.length - 1].orderSeq + 1)
      } else {
        params += ',orderSeq=' + zEnBase64('1')
      }

      const data = { token: getToken(), parameterArray: params, functionID: global.functionID }
      const { header } = await createChainFrequencyData(data)
      if (header.code === 0) {
        await this.saveData(false)
        await this.saveData(false)
        this.$nextTick(() => {
          const container = this.$el.querySelector('.el-table__body-wrapper')
          container.scrollTop = container.scrollHeight
        })
        // this.dialogFormVisible = false // 关闭对话框
        // this.$message({
        //   message: '创建成功',
        //   type: 'success'
        // })
      } else {
        this.$message({
          message: header.msg,
          type: 'error'
        })
      }
      this.loadingBtn = false // 提交按钮可用
      this.loadingBtnTitle = '确定'
    },
    async saveData(showMessage) {
      this.loadingBtn = true
      console.warn(this.list)
      if (this.list.length > 0) {
        const arr = []
        let i = 0
        this.list.map(data => {
          const obj = {}
          obj.ID = data.ID
          obj.orderSeq = ++i
          obj.centerFrequency = isNotEmpty(data.centerFrequency) ? data.centerFrequency.replace(/,/g, '') : ''
          obj.coupling = isNotEmpty(data.coupling) ? data.coupling : ''
          obj.gain = isNotEmpty(data.gain) ? data.gain : ''
          obj.loss = isNotEmpty(data.loss) ? data.loss : ''
          arr.push(obj)
        })
        const { header } = await UploadChainFrequencyData({ token: getToken(), data: arr })
        if (header.code === 0) {
          await this.getList()
          if (showMessage) {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          }
        } else {
          this.$message({
            message: header.msg,
            type: 'error'
          })
        }
      } else {
        await this.getList()
      }
      this.loadingBtn = false // 提交按钮可用
      this.loadingBtnTitle = '确定'
    },
    async save() {
      await this.saveData(false)
      await this.saveData(true)
    },
    confirmEdit(row) {
      console.log(row)
      let params = ''
      params += 'ID=' + row.ID
      // params += ',stationID=' + (isNotEmpty(this.temp.stationID) ? zEnBase64(this.temp.stationID) : '')
      // params += ',chainID=' + (isNotEmpty(this.temp.chainID) ? zEnBase64(this.temp.chainID) : '')
      // params += ',chainFrequencyDefineID=' + (isNotEmpty(this.temp.chainFrequencyDefineID) ? zEnBase64(this.temp.chainFrequencyDefineID) : '')
      // params += ',name=' + (isNotEmpty(this.temp.name) ? zEnBase64(this.temp.name) : '')
      // params += ',shortName=' + (isNotEmpty(this.temp.shortName) ? zEnBase64(this.temp.shortName) : '')
      // params += ',orderSeq=' + (isNotEmpty(this.temp.orderSeq) ? zEnBase64(this.temp.orderSeq) : '')
      // params += ',componentID=' + (isNotEmpty(this.temp.componentID) ? zEnBase64(this.temp.componentID) : '')
      params += ',centerFrequency=' + (isNotEmpty(row.centerFrequency) ? zEnBase64(row.centerFrequency.replace(/,/g, '')) : '')
      // params += ',bandWidth=' + (isNotEmpty(this.temp.bandWidth) ? zEnBase64(this.temp.bandWidth.replace(/,/g, '')) : '')
      params += ',coupling=' + (isNotEmpty(row.coupling) ? zEnBase64(row.coupling) : '')
      params += ',loss=' + (isNotEmpty(row.loss) ? zEnBase64(row.loss) : '')
      params += ',gain=' + (isNotEmpty(row.gain) ? zEnBase64(row.gain) : '')

      const data = { token: getToken(), parameterArray: params, functionID: global.functionID }
      updateChainFrequencyData(data).then(response => {
        if (response.header.code === 0) {
          row.edit = false
          this.getList()
          // this.$message({
          //   message: '更新成功',
          //   type: 'success'
          // })
          // this.$notify({
          //   title: '更新成功',
          //   message: this.temp.name,
          //   type: 'success',
          //   duration: global.notify.durationShort
          // })
        } else {
          // this.loadingBtn = false // 提交按钮可用
          // this.loadingBtnTitle = '确定'
          this.$notify({
            title: '更新失败',
            message: response.header.msg,
            type: 'error',
            duration: global.notify.duration
          })
        }
      }).catch(err => {
        this.loadingBtn = false // 提交按钮可用
        this.loadingBtnTitle = '确定'
        console.error(err)
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否确认删除 ' + row.centerFrequency + '?', {
        type: 'warning',
        closeOnClickModal: false, // 点击区域外不可关闭
        closeOnPressEscape: false // 按ESC不可关闭
      }).then(async() => {
        const params = { token: getToken(), parameterArray: 'ID=' + row.ID, functionID: global.functionID }
        const { header } = await deleteChainFrequencyData(params)
        if (header.code === 0) {
          await this.saveData(false)
          await this.saveData(false)
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: header.msg,
            type: 'error'
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '序号', '中心频率', '频率带宽', '耦合度', '增益', '损耗']
        const filterVal = ['ID', 'orderSeq', 'centerFrequency', 'bandWidth', 'coupling', 'gain', 'loss']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.excel.filename,
          autoWidth: this.excel.autoWidth,
          bookType: this.excel.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'OPERATETIME') {
          return moment(v[j]).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return v[j]
        }
      }))
    },
    handleCurrentChange(row) {
      this.currentRow = row
      this.selectedIndex = row.index
      // row.centerFrequency = row.centerFrequency != null ? controlAmount(row.centerFrequency) : ''
      // row.edit = true
      console.log(row)
      // alert(this.selectedIndex)
    },
    closeDlg() {
      this.visible = false
      this.$parent.chainFreqDataVisible = false
    },
    rowClass({ row, rowIndex }) {
      if ((this.selectedIndex) === rowIndex && row.edit) {
        // return 'edit'
      }
    },
    tableClass({ row, rowIndex }) {
      row.index = rowIndex
      if (row.edit) {
        // return 'edit'
      }
      if (rowIndex % 2 === 0) {
        return 'yellow2'
      }
      return ''
    },
    controlAmount: controlAmount
  }
}
</script>

<style>
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .sortable-ghost{
    opacity: .8;
    color: #fff!important;
    background: #42b983!important;
  }
</style>

<style scoped>
  .icon-star{
    margin-right:2px;
  }
  .drag-handler{
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
  .show-d{
    margin-top: 15px;
  }
</style>
<style>
  .el-table .yellow {
    background: #fdf9f0;
  }
  .el-table .yellow2 {
    background: #fdfbf7;
  }
  .el-table .edit {
    background: #d9991b;
  }
</style>
